package com.examples.AppoointmentManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class LocateOnMapActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
        
                
      //creating Spinner reference for Id map_view(Spinner) and assigning
        Spinner spinner1 = (Spinner) findViewById(R.id.map_view);
      //using ArrayAdapter class for loading [views_array] array values into spinner
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
                this, R.array.views_array, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter1);
        
      //creating Button reference for Id search(Button) and assigning
        Button search=(Button)findViewById(R.id.search);
        //setting onClickListener for the search button
        search.setOnClickListener(this);
    
    }

	public void onClick(View view) {
		
		//checking whether the button clicked is search or not
		if(view.getId() == R.id.search){
			
			EditText B_name=(EditText)findViewById(R.id.place);
			//validating the brandname textbox if it contains a value then search method is called
			if(B_name.getText().length() == 0)
			{
				 // Creating the alert box
	            AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
	            // Setting the message to display
	            alertbox.setMessage("Enter Place Name...");
	            // Add a neutral button to the alert box and assign a click listener
	            alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() {
	            	// Click listener on the neutral button of alert box
	                public void onClick(DialogInterface arg0, int arg1) {
	                	return;
	                }
	            });
	            // showing the alert box
	            alertbox.show();
	        }
			else    
    		search();
    	}
		
	}
	//retrieves longitude,latitude values from the user input
	public void search()
	{
		try {
			//creating references for text boxes and spinners and assigning them accordingly
			EditText brand_name=(EditText)findViewById(R.id.place);
			EditText city = (EditText)findViewById(R.id.city);
			EditText adress=(EditText)findViewById(R.id.address);
			Spinner mySpinner1 = (Spinner)findViewById(R.id.map_view);
			
			//retrieving values from references created into strings
			String brandname=brand_name.getText().toString();
			String city1=city.getText().toString();
			String address=adress.getText().toString();
			String map_view = mySpinner1.getSelectedItem().toString();
			
			//concatenating the string values into a string location
			String location=brandname+" "+address+" "+city1+" "+"india";
			
			//removing spaces from the string and replacing accordingly
			location=location.replaceAll("\\s","+");
			
			map_view=map_view.replaceAll("\\s","");
			
			String urltext = "https://maps.googleapis.com/maps/api/geocode/json?address="+location+"&sensor=true";
			
			//Toast.makeText(this, urltext, Toast.LENGTH_LONG).show();
			//reading the contents of url into a string using InputStreamReader
			URL url;
			url = new URL(urltext);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    		String inputLine,json="";
    		while ((inputLine = in.readLine()) != null) {
    			json=json+inputLine;
    		}		
    		in.close();
    		//Toast.makeText(this, json, Toast.LENGTH_LONG).show();
    		//creating a JSON object and passing json string 
    		JSONObject json1=new JSONObject(json);
    		//creating JSON array object for retrieving values
    		JSONArray results=json1.getJSONArray("results");
    		//retrieving latitude and longitude from the JSON array 
    		String lat=((JSONObject) results.get(0)).getJSONObject("geometry").getJSONObject("location").getString("lat");
    		String lng=((JSONObject) results.get(0)).getJSONObject("geometry").getJSONObject("location").getString("lng");
    		
    		//creating Intent and sending longitude,latitude and map view values
    		Intent intent = new Intent(LocateOnMapActivity.this, ShowOnMapActivity.class);
    		intent.putExtra("lat",lat);
    		intent.putExtra("lng",lng);
    		intent.putExtra("map_view",map_view);
    		//starting new Activity 
    		startActivity(intent);
		}
		catch (MalformedURLException e) {
			//Exception thrown when the given URL or String cannot be parsed.	
				Toast.makeText(this, "Entered Loacation May Contain Invalid Data", Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
		catch (NetworkOnMainThreadException e) {
	//Exception thrown when networking operation is performed on its main thread depending on version used
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		catch ( ActivityNotFoundException e) {
			//Exception thrown when Activity can not be found because one of its variants failure
			Toast.makeText(this, "Problem in Starting Activity", Toast.LENGTH_LONG).show();
		    e.printStackTrace();
		}
		catch (JSONException e) {
			//Exception thrown when things are amiss
			Toast.makeText(this, "Please Enter correct location", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		catch (IOException e) {
					Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
					e.printStackTrace();
				}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}